import fg from "fast-glob";
import fs from "fs-extra";
import path from "path";
import { UnityHelper } from "./UnityHelper.js";
import { strArrayToMap } from "./vendor.js";
import { toolchain } from "../toolchain.js";

export class Missing {
    public async findMissing(): Promise<void> {
        const outFile = `tmp/${toolchain.opts.projectName}.missing.txt`;
        await fs.ensureFile(outFile);
        await fs.writeFile(outFile, '', 'utf-8');

        const allGUIDs = await UnityHelper.collectExistingGUID(path.join(toolchain.opts.projectRoot, 'Assets'));
        const allGUIDs2 = await UnityHelper.collectExistingGUID(path.join(toolchain.opts.projectRoot, 'Library/PackageCache'));
        const guidMap = strArrayToMap(allGUIDs.concat(allGUIDs2));
        
        const uiRoot = path.join(toolchain.opts.projectRoot, 'Assets');
        // const prefabs = await fg('**/*.mat', { cwd: uiRoot });
        const prefabs = await fg(['**/*.prefab', '**/*.mat'], { cwd: uiRoot });
        // const prefabs = await fg(['AssetSources/scene/*.unity'], { cwd: uiRoot });
        for (const prefab of prefabs) {
            const file = path.join(uiRoot, prefab);
            const content = await fs.readFile(file, 'utf-8');
            const lines = content.split(/\r?\n/);
            for (let i = 0, len = lines.length; i < len; i++) {
                const rst = lines[i].match(/guid: (\w{32})/);
                // 一些内置的比如Mesh Filter之类的guid是0000000000000000e000000000000000
                if (rst != null && !rst[1].startsWith('000000000') && !guidMap[rst[1]]) {
                    await fs.appendFile(outFile, file + ':' + (i + 1) + '\n', 'utf-8');
                    console.error(file + ':' + (i + 1));
                    if (file.endsWith('.mat')) {
                        await toolchain.usageFinder.lookUp(file);
                    }
                }
            }
        }
    }
}
